package com.douyuehan.doubao.wechatpay.utils;

import com.douyuehan.doubao.common.exception.ArgumentException;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class Md5Util {

    private Md5Util() {
    }

    /**
     * Return a hash according to the MD5 algorithm of the given String.
     *
     * @param s The String whose hash is required
     * @return The MD5 hash of the given String
     */
    public static String md5(String s) {

        return DigestUtils.md5Hex(s).toLowerCase();
    }

    public static byte[] md5Bytes(byte[] srcBytes) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        messageDigest.update(srcBytes);
        // 获得密文
        byte[] md = messageDigest.digest();
        return md;
    }


    /**
     * 签名字符串
     * @param text 需要签名的字符串
     * @param key 密钥
     * @return 签名结果
     */
    public static String sign(String text, String key) {
        text = text + key;
        return DigestUtils.md5Hex(getContentBytes(text, "utf-8"));
    }

    /**
     * 签名字符串
     * @param text 需要签名的字符串
     * @param key 密钥
     * @param input_charset 编码格式
     * @return 签名结果
     */
    public static String sign(String text, String key, String input_charset) {
        text = text + key;
        return DigestUtils.md5Hex(getContentBytes(text, input_charset));
    }

    /**
     * @param content
     * @param charset
     * @return
     * @throws java.security.SignatureException
     * @throws UnsupportedEncodingException
     */
    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new ArgumentException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset, 500);
        }
    }
}
